/**
 * @author mengxia.jing
 * @description 封装Axios
 */
import axios from 'axios'
// 引入Store实例,获取token数据
import Store from '../store'
// 实现通用配置和业务配置分离(解耦)
const Axios = axios.create({
  baseURL: '/apis',
  timeout: 5000
})
// 请求前的拦截，如需要token
// 拦截钩子函数
Axios.interceptors.request.use(function (config) {
  let paths = ['/user/validate/code', '/user/app/login']
  if (paths.includes(config.url)) {
    return config
  } else {
    // 获取vuex中的token
    const token = Store.getters['common/token']
    if (!!token) {
      config.headers.token = token
      return config
    } else {
      return Promise.reject({
        code: 400,
        message: '您已被拦截，没有访问这个接口的权限!'
      })
    }
  }
})

function Ajax(req) {
  return new Promise(resolve => {
    Axios.request({
      url: req.url,
      method: req.method || 'POST',
      // 请求体中传递参数
      data: req.data || {},
      // 请求地址中传递参数
      params: req.params || {},
    }).then(({
      data
    }) => {
      resolve(data)
    }).catch(e => {
      console.log(e)
      resolve({
        code: 999,
        message: '异步请求失败'
      })
    })
  })
}
export default Ajax
